package com.lmb.controller;

import com.lmb.bean.AdministratorLogin;
import com.lmb.bean.AdministratorLogin;
import com.lmb.service.Login2Service;
import com.lmb.service.LoginService;
import com.lmb.util.CaptchaUtil;
import com.lmb.util.Result;
import com.lmb.util.SyS;
import com.lmb.util.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/login2")
@CrossOrigin
public class Login2Controller {
    @Autowired
    Login2Service login2Service;

    @GetMapping("/captcha")
    public Object getCaptcha(){
        return Result.success(CaptchaUtil.getCaptcha());
    }
    @PostMapping("/dologin")
    public Result login(AdministratorLogin administratorLogin, @RequestParam("captcha") String captcha, @RequestParam("key") String key){
        //验证验证码
        if (!CaptchaUtil.checkCaptcha(key,captcha)){
            return Result.fail(500,"验证码错误");
        }
        //登录
        try {
            String token = login2Service.login(administratorLogin);
            //删除验证码
            return Result.success("登陆成功",token);
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail(500,e.getMessage());
        }
    }
    @GetMapping("/getlogin")
    public Result getlogin(HttpServletRequest request, HttpSession session){
        String token=request.getHeader(SyS.TOKEN_AUTHORIZATION);//获取token
        try {
            AdministratorLogin administratorLogin=login2Service.getlogin(token);
            return Result.success(administratorLogin);
        }catch (RuntimeException e) {
            TokenUtil.removeToken(token);
            return Result.fail(500,e.getMessage());
        } catch (Exception e) {
            return Result.fail(500,"登录异常：系统错误");
        }

    }
}
